import 'package:stacked/stacked.dart';
import 'package:vista/shared/models/challenge_submission.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/relation_bond.dart';
import 'package:vista/shared/services/theme_challenge_service.dart';

/// 挑战详情视图模型
/// 管理挑战详情页面的数据和状态
class ChallengeDetailViewModel extends BaseViewModel {
  final ThemeChallengeService _themeChallengeService;
  final AuthFocus _authFocus;
  final RelationBond _relationBond;
  final String submissionId;

  ChallengeDetailViewModel(
    this._themeChallengeService,
    this._authFocus,
    this._relationBond,
    this.submissionId,
  );

  ChallengeSubmission? _submission;
  ChallengeSubmission? get submission => _submission;

  UserFrame? _author;
  UserFrame? get author => _author;

  UserFrame? _currentUser;
  UserFrame? get currentUser => _currentUser;

  bool _isFollowing = false;
  bool get isFollowing => _isFollowing;

  /// 初始化数据
  Future<void> initialize() async {
    setBusy(true);
    try {
      _currentUser = await _authFocus.getCurrentUser();
      await _loadSubmission();
      await _loadAuthor();
      await _checkFollowingStatus();
    } finally {
      setBusy(false);
    }
  }

  /// 加载挑战投稿数据
  Future<void> _loadSubmission() async {
    final allSubmissions = await _themeChallengeService.getAllSubmissions();
    _submission = allSubmissions.firstWhere(
      (submission) => submission.id == submissionId,
      orElse:
          () =>
              allSubmissions.isNotEmpty
                  ? allSubmissions.first
                  : throw Exception('Submission not found'),
    );
    notifyListeners();
  }

  /// 加载发布者信息
  Future<void> _loadAuthor() async {
    if (_submission == null) return;

    final allUsers = await _authFocus.getUsers();
    _author = allUsers.firstWhere(
      (user) => user.id == _submission!.authorId,
      orElse:
          () =>
              allUsers.isNotEmpty
                  ? allUsers.first
                  : throw Exception('User not found'),
    );
    notifyListeners();
  }

  /// 检查是否已关注
  Future<void> _checkFollowingStatus() async {
    if (_currentUser == null || _author == null) {
      _isFollowing = false;
      notifyListeners();
      return;
    }

    _isFollowing = await _relationBond.isFollowing(
      followerId: _currentUser!.id,
      followingId: _author!.id,
    );
    notifyListeners();
  }

  /// 关注/取消关注用户
  Future<void> toggleFollow() async {
    if (_currentUser == null || _author == null) return;

    if (_isFollowing) {
      await _relationBond.unfollowUser(
        followerId: _currentUser!.id,
        followingId: _author!.id,
      );
    } else {
      await _relationBond.followUser(
        followerId: _currentUser!.id,
        followingId: _author!.id,
      );
    }

    await _checkFollowingStatus();
  }
}
